<template>
  <div>
    <!--        面包屑导航-->
    <breadcrumb :navData="navData"></breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        effect="dark"
        show-icon
        :closable="false"
      ></el-alert>
      <!-- 选择商品分类 -->
      <div class="block">
        <span class="demonstration">选择商品分类：</span>
        <el-cascader
          v-model="value"
          :options="options"
          :props="cas_pop"
          @change="handleChange"
          clearable
        ></el-cascader>
      </div>
      <!-- 动态参数 -->
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            @click="add_visable=true"
            :disabled="isBtnDisabled"
          >添加参数</el-button>
          <!-- 表格 -->
          <el-table :data="manyData" border style="width: 100%">
            <el-table-column width="50" type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(tag,index) in scope.row.attr_values"
                  closable
                  :disable-transitions="false"
                  @close="onDeleteAttr(scope.row, index)"
                >{{ tag }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="onAddAttr(scope.row)"
                  @blur="onAddAttr(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="onShowAddAttrInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" width="50" type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="500"></el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <!--                        修改-->
                <el-button
                  type="primary"
                  size="mini"
                  @click="onEditParams(scope.row)"
                  icon="el-icon-edit"
                >修改</el-button>
                <!--                        删除-->
                <el-button
                  type="danger"
                  size="mini"
                  @click="onDeleteParams(scope.row)"
                  icon="el-icon-delete"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            @click="add_visable=true"
            :disabled="isBtnDisabled"
          >添加参数</el-button>
          <!-- 表格 -->
          <el-table :data="valsData" border style="width: 100%">
            <!-- 展开 -->
            <el-table-column width="50" type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(tag,index) in scope.row.attr_values"
                  closable
                  :disable-transitions="false"
                  @close="onDeleteAttr(scope.row, index)"
                >{{ tag }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="onAddAttr(scope.row)"
                  @blur="onAddAttr(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="onShowAddAttrInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" width="50" type="index"></el-table-column>
            <el-table-column prop="name" label="参数名称" width="500"></el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <!--                        修改-->
                <el-button
                  type="primary"
                  size="mini"
                  @click="onEditParams(scope.row)"
                  icon="el-icon-edit"
                >修改</el-button>
                <!--                        删除-->
                <el-button
                  type="danger"
                  size="mini"
                  @click="onDeleteParams(scope.row)"
                  icon="el-icon-delete"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!--添加参数表单-->
      <el-dialog :title="'添加'+titleText" :visible.sync="add_visable">
        <el-form :model="addParams" :rules="addParamsRules" ref="addParamsForm" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addParams.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="add_visable = false">取 消</el-button>
          <el-button type="primary" @click="onAddParams">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改弹出表单 -->
      <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "VueShopsParams",

  data() {
    return {
      navData: ["商品管理", "参数列表"],
      // 级联选择器v-model
      value: [],
      options: [],
      // 级联选择器配置
      cas_pop: {
        checkStrictly: true,
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      curEditId: "",
      activeName: "many",
      // 动态表格
      manyData: [],
      // 静态表格
      valsData: [],
      //添加参数对话框
      add_visable: false,
      // 添加参数绑定
      addParams: {
        attr_name: "",
        attr_sel: "",
      },
      //添加参数验证
      addParamsRules: {
        attr_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      // 失焦获取的内容
      curAddAttr: "",
      // 修改弹出
      editDialogVisible: false,
      // 修改表单
      editForm: {},
      // 修改表单验证
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
    };
  },

  mounted() {},
  created() {
    this.getclas();
  },
  computed: {
    cateId() {
      return this.value.length === 3 ? this.value[2] : null;
    },
    // 不等于3级分类禁用
    isBtnDisabled() {
      return this.value.length !== 3;
    },
    // 弹出框赋值
    titleText() {
      return this.activeName === "many" ? "动态参数" : "静态属性";
    },
  },
  methods: {
    // 商品分类数据获取
    async getclas() {
      this.dialogFormVisible = true;
      const cascader = await this.axios.get("/categories");
      console.log(cascader);
      this.options = cascader.data.data;
    },
    // 选项卡点击切换
    handleClick(tab, event) {
      console.log(tab, event);
      console.log(this.activeName);
      this.handle_data();
    },
    // 连级选择器hover事件
    handleChange(value) {
      console.log(value);
      this.handle_data();
    },
    // 获取表格动态参数静态参数
    async handle_data() {
      if (this.value.length !== 3) {
        this.manyData = [];
        this.valsData = [];
        this.value = [];
        return this.$message.error("只允许为三级分类设置参数！");
      }
      console.log(this.cateId, this.activeName);
      const handle_data = await this.axios.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      );
      console.log(handle_data, "11");

      handle_data.data.data.forEach((item) => {
        item.attr_values = item.attr_vals ? item.attr_vals.split(",") : [];
        item.inputVisible = false;
        // item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.manyData = handle_data.data.data;
      } else {
        this.valsData = handle_data.data.data;
      }
    },
    //确定添加参数
    onAddParams() {
      this.$refs.addParamsForm.validate(async (valid) => {
        if (valid) {
          const okparamse = await this.axios.post(
            `categories/${this.cateId}/attributes`,
            {
              attr_name: this.addParams.attr_name,
              attr_sel: this.activeName,
            }
          );
          this.addParams.attr_name = "";
          if (okparamse.data.meta.status == 201) {
            this.$message.success("成功");
            this.handle_data();
            this.add_visable = false;
          } else {
            this.$message.error("失败");
          }
        }
      });
    },

    //添加属性input框显示
    onShowAddAttrInput(row) {
      // 显示input框
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // input失焦获取当前输入的内容
    onAddAttr(row) {
      this.curAddAttr = row.inputValue;
      //清空输入框的内容
      row.inputValue = "";
      // 关闭
      row.inputVisible = false;
      if (this.curAddAttr.trim().length === 0) return;
      this.updateAttrValues(row);
    },

    // New Tag属性删除
    onDeleteAttr(row, index) {
      row.attr_values.splice(index, 1);
      this.updateAttrValues(row);
    },
    //更新New Tag属性
    async updateAttrValues(row) {
      console.log(row);

      let curAttrVlas = row.attr_values.join(",");
      let attr_vals = this.curAddAttr
        ? curAttrVlas + "," + this.curAddAttr
        : curAttrVlas;
      const curets = await this.axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: attr_vals,
        }
      );
      if (curets.data.meta.status == 200) {
        this.$message.success("成功");
        row.attr_vals = curets.data.data.attr_vals;
        row.attr_values = row.attr_vals.split(",");
      } else {
        this.$message.error("失败");
      }
    },

    //修改参数弹出回填数据
    async onEditParams(row) {
      console.log(row.attr_id);
      this.editDialogVisible = true;
      const edits_list = await this.axios.get(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          params: { attr_sel: this.activeName },
        }
      );
      console.log(edits_list);
      if (edits_list.data.meta.status == 200) {
        this.$message.success("成功");
        this.editForm = edits_list.data.data;
        console.log(this.editForm);
      } else {
        this.$message.error("失败");
      }
    },
    //确定修改
    async editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          const editforms = await this.axios.put(
            `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
            { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
          );
          if (editforms.data.meta.status == 200) {
            this.$message.success("成功");
            this.handle_data();
            this.editDialogVisible = false;
          } else {
            this.$message.error("失败");
          }
        }
      });
    },
    //删除参数
    async onDeleteParams(row) {
      console.log(row.attr_id);
      const deletes = await this.axios.delete(
        `categories/${this.cateId}/attributes/${row.attr_id}`
      );
      console.log(deletes);
      if (deletes.data.meta.status == 200) {
        this.$message.success("删除成功");
        this.handle_data();
      } else {
        this.$message.error("删除失败");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.block {
  text-align: left;
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>